<script setup lang="ts">
import { ref } from 'vue';

class HISTORY_INFO
{
  name: string;
  modId: string;

  constructor(name: string="Unknow", modId: string="")
  {
    this.name = name;
    this.modId = modId;
  }
}

// @ts-ignore
class MOD_RENDER_INFO
{
  name: string = "";
  modId: string = "";
  errorMsg: string = "";
  errorState: boolean = false;
  diamond: number = 0;
  htmlDoc: string = "";
  stars: number = 0;
  iconUrl: string = "";
  downloadCount: number = 0;
  constructor(name: string="", modId: string="", errorState: boolean = false)
  {
    this.name = name;
    this.modId = modId;
    this.errorState = errorState;
  }

  setDownloadCount(downloadCount: number)
  {
    this.downloadCount = downloadCount;
    return this;
  }

  setHtmlDoc(htmlDoc: string)
  {
    this.htmlDoc = htmlDoc;
    return this;
  }

  setIconUrl(iconUrl: string)
  {
    this.iconUrl = iconUrl;
    return this;
  }

  setStars(stars: number)
  {
    this.stars = stars;
    return this;
  }

  setDiamond(diamond: number)
  {
    this.diamond = diamond;
    return this;
  }

  setErrorMsg(errorMsg: string)
  {
    this.errorMsg = errorMsg;
    this.errorState = true;
    return this;
  }

  static createError(error: string=""): MOD_RENDER_INFO
  {
    return new MOD_RENDER_INFO("Error", "Error", true).setErrorMsg(error);
  }
}

const searchText = ref('');
const historyList = ref<HISTORY_INFO[]>([]);
const modRenderInfo = ref<MOD_RENDER_INFO | null>(null);
const isLoading = ref(false);
let _lastRenderObj: object = {};

// 更新历史记录渲染信息
function UPDATE_HIS_RENDER_LIST()
{
  try {
      historyList.value = [];
      // @ts-ignore
      _API_GET_HIS_RENDER_LIST().then((jsonString) => {
      const arr = JSON.parse(jsonString);
      arr.forEach((item: JSON) => {
        // @ts-ignore
        historyList.value.push(new HISTORY_INFO(item["name"], item["modId"]));
      });
  });;
  } catch (_) {}
}

function CPP_SEARCH_MOD_INFO(modId: string)
{
  isLoading.value = true;
  // @ts-ignore
  _API_SEARCH_MOD_INFO(modId);
}

// MOD渲染数据更新
function updateRenderInfo()
{
  isLoading.value = false;
  // @ts-ignore
  const renderJo: any = _lastRenderObj;
  // 无效的MOD数据
  if(renderJo.cpp_state != 0)
  {
    modRenderInfo.value = MOD_RENDER_INFO.createError(renderJo.cpp_error);
    return;
  }
  UPDATE_HIS_RENDER_LIST();
  // 有效的MOD数据
  modRenderInfo.value = new MOD_RENDER_INFO(renderJo.entity.res_name, renderJo.entity.item_id)
  .setDiamond(renderJo.entity.diamond)
  .setStars(renderJo.entity.stars)
  .setIconUrl(renderJo.entity.title_image_url)
  .setHtmlDoc(renderJo.entity.info).setDownloadCount(renderJo.entity.download_num);
}

function onTick()
{
  // @ts-ignore
  if(!webui.ipcRenderInfo)
  {
    return;
  }
  // @ts-ignore
  if(webui.ipcRenderInfo != _lastRenderObj)
  {
    // @ts-ignore
    _lastRenderObj = webui.ipcRenderInfo;
    updateRenderInfo();
  }
}

// @ts-ignore
document.addEventListener('DOMContentLoaded', function() {
    // @ts-ignore
    if (typeof webui !== 'undefined') {
        // 尝试循环检查后端链接状态
        const timerId = setInterval(() => {
          // @ts-ignore
          if (webui.ipcConnectedState)
          {
            clearInterval(timerId);
            // 进入消息循环(tick)
            setInterval(() => {
              // @ts-ignore
              if (webui.ipcConnectedState)
              {
                onTick();
              }
            }, 50);
            UPDATE_HIS_RENDER_LIST();
          } else {
            console.log("等待IPC链接...");
          }
        }, 20);
    } else {
      console.log('webui is not defined.');
    }
});

// 查询处理
function onSearch()
{
  if (!searchText.value) return;
  CPP_SEARCH_MOD_INFO(searchText.value);
  // searchResult.value = searchText.value;
  // historyList.value.push(new HISTORY_INFO("NAME", "MODID"));
}

// 历史点击处理
function onHistoryClick(item: HISTORY_INFO)
{
  searchText.value = item.modId;
}

// 清除搜索框
function onClear() {
  searchText.value = '';
}
</script>

<template>
  <div style="width: 100%; height: 100vh; background: var(--color-bg-1);">
    <a-layout style="height: 100%;">
      <!-- 左侧侧边栏 -->
      <a-layout-sider :width=250 style="padding: 12px;">
          <!-- 搜索区域 -->
          <a-space direction="vertical" :size="16" style="width: 100%;">
            <a-input
              v-model="searchText"
              placeholder="请输入MODID"
              allow-clear
              @press-enter="onSearch"
              @clear="onClear"
            />
            <a-button type="primary" shape="round" long @click="onSearch">查询</a-button>
          </a-space>

          <!-- 历史记录标题 -->
          <a-typography-title :heading="5" style="margin-top: 10px;">历史记录</a-typography-title>

        <!-- 历史记录列表 -->
        <a-list
          :data="historyList"
          size="small"
          :bordered="false"
          style="margin-top: 8px;"
        >
          <template #item="{ item }">
            <a-list-item
              @click="onHistoryClick(item)"
              style="cursor: pointer;"
            >
              <a-tag type="info"> {{ item.name }} </a-tag>
              <!-- <a-tag type="info">{{ item.modId }}</a-tag> -->
            </a-list-item>
          </template>
        </a-list>

      </a-layout-sider>

      <!-- 右侧内容展示区域 -->
    <a-layout-content style="padding: 13px;">
      <a-typography-title :heading="5">查询结果</a-typography-title>

      <div v-if="modRenderInfo">
        <div v-if="modRenderInfo.errorState">
          <a-alert> MOD查询遇到错误: {{ modRenderInfo.errorMsg }} </a-alert>
        </div>
        <div v-else>
          <a-card
            :title="modRenderInfo.name"
            :extra="modRenderInfo.modId"
            style="width: 100%;"
          >
          <a-row :gutter="16">
            <!-- 左侧头像 -->
            <a-col :span="4">
              <img
                :src="modRenderInfo.iconUrl"
                style="width: 80%; height: auto; border-radius: 3px;"
              />
            </a-col>

            <!-- 右侧信息 -->
            <a-col :span="20">
              <a-row :gutter="12">
                <a-col :span="8">
                  <div><strong>钻石：</strong>{{ modRenderInfo.diamond }}</div>
                </a-col>
                <a-col :span="8">
                  <div><strong>得分：</strong>{{ modRenderInfo.stars }}</div>
                </a-col>
                <a-col :span="8">
                  <div><strong>下载量：</strong>{{ modRenderInfo.downloadCount }}</div>
                </a-col>
              </a-row>

              <a-divider></a-divider>
            </a-col>
            <div class="dynamic-html-container" v-html="modRenderInfo.htmlDoc"></div>
          </a-row>
          </a-card>
        </div>
      </div>

      <div v-else>
        <div v-if="isLoading">
            <a-alert type="info">正在查询MOD信息...</a-alert>
        </div>
        <div v-else>
            <a-alert> 请在左侧输入MODID进行查询。 </a-alert>
        </div>
      </div>
    </a-layout-content>
    </a-layout>
  </div>
</template>

<style scoped>
/* 给所有可滚动元素隐藏滚动条，但允许滚动 */
*::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Edge */
}

* {
  -ms-overflow-style: none;  /* IE 和 Edge */
  scrollbar-width: none;     /* Firefox */
}

.dynamic-html-container {
  max-width: 100vw;       /* 最大宽度限制为视口宽 */
  overflow-wrap: break-word; /* 文字超长自动换行 */
  word-break: break-word;
  box-sizing: border-box;
  padding: 0 12px;        /* 防止紧贴边缘 */
}

.dynamic-html-container * {
  max-width: 100%;        /* 所有子元素最大宽度不超父容器 */
  box-sizing: border-box;
}

.dynamic-html-container img {
  max-width: 100%;        /* 图片宽度限制为父容器宽度 */
  height: auto;
  display: block;
  object-fit: contain;
}
</style>
